/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mudalov.rec.web.filters;

import com.mudalov.rec.web.SessionBean1;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author MU
 */
public class AuthenticationFilter implements Filter {

   public void init(FilterConfig config) throws ServletException {
        //No-op
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                                                           throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        String requestUrl = httpRequest.getRequestURL().toString();
        HttpSession session = httpRequest.getSession();
        SessionBean1 sessionBean = (SessionBean1)session.getAttribute("SessionBean1");
        boolean accessDenied = false;
        if (sessionBean != null
                && sessionBean.getCurrentUser() != null) {
            if ((requestUrl.contains("Teacher")
                    && !sessionBean.getCurrentUser().isTeacher())
                    || (requestUrl.contains("Admin")
                    && !sessionBean.getCurrentUser().isAdmin())
                    || (requestUrl.contains("Student")
                    && !sessionBean.getCurrentUser().isStudent())
                    || requestUrl.contains("resources")) {
                    accessDenied = true;
            }
        } else {
            accessDenied = true;
        }
        if (!accessDenied) {
             chain.doFilter(request, response);
        } else {
            ((HttpServletResponse)response).sendRedirect("/faces/StartPage.jsp");
        }
    }

    public void destroy() {
        //No-op
    }

}
